package com.taiji.dianthus.common;


import com.taiji.dianthus.domain.sys.DSysRole;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.dto.MenuDto;
import com.taiji.dianthus.security.DianthusSecurityMetadataSource;
import com.taiji.dianthus.security.SecurityUtil;
import com.taiji.dianthus.service.sys.MenuRoleService;
import com.taiji.dianthus.service.sys.RoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;


/**
 * Controller 公共方法类
 *
 * @author H.M
 */
public class BasicController {

    @Autowired
    private DianthusSecurityMetadataSource dianthusSecurityMetadataSource;

    @Autowired
    private RoleUserService roleUserService;

    @Autowired
    private MenuRoleService menuRoleService;

    /**
     * 获得当前登录用户对象
     *
     * @return
     */
    public DSysUser currentUser() {
        DSysUser currentUser = dianthusSecurityMetadataSource.currentUser();
        if (currentUser == null) {
            return null;
        }
        if (currentUser instanceof DSysUser) {
            return currentUser;
        } else {
            return null;
        }
    }

    /**
     * 获取用户菜单
     *
     * @return
     */
    public List<MenuDto> listMenu() {
        List<MenuDto> menuList = new ArrayList<>();
        DSysUser user = dianthusSecurityMetadataSource.currentUser();
        if (null != user) {
            // 获取用户角色
            Set<DSysRole> roles = roleUserService.listByUser(user.getId());
            menuList = menuRoleService.getMenuByRoles(roles);
        }
        return menuList;
    }

    /**
     * 处理页码
     *
     * @param pageSize
     * @return
     */
    public Integer getPageSize(Integer pageSize) {
        if (null == pageSize) {
            pageSize = 10;
        }
        return pageSize;
    }

    /**
     * 处理当前页
     *
     * @param currentPage
     * @return
     */
    public Integer getCurrentPage(Integer currentPage) {
        //从前台传来的页数
        if (null == currentPage || currentPage == 0) {
            currentPage = 0;
        } else {
            currentPage = currentPage - 1;
        }
        return currentPage;
    }
}
